from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware

import predict

app = FastAPI(title="法律判决预测 API")

# 允许跨域请求
app.add_middleware(
		CORSMiddleware,
		allow_origins=["*"],  # 生产环境需指定具体前端域名
		allow_credentials=True,
		allow_methods=["*"],
		allow_headers=["*"],
)


class CaseRequest(BaseModel):
	text: str  # 案情描述文本


class PredictionResponse(BaseModel):
	similar_cases: str
	judgment_result: str
	judicial_interpretation: str
	verdict: str


@app.post("/predict", response_model=PredictionResponse)
async def predict_case(request: CaseRequest):
	# 调用预测函数
	result_json, case_list = predict.predict(request.text)
	judgment_result = predict.accusation_json2str(result_json)
	
	# 生成司法解释
	text1 = request.text + judgment_result + "请根据犯罪事实，判决结果，给出合理的司法解释。（仅输出司法解释，其他内容均不输出）"
	response = predict.think(text1, stream=False)
	judicial_interpretation = response["output"]["choices"][0]["message"]["content"]
	
	# 生成判决书
	text3 = f"{request.text}\n{text1}\n{judicial_interpretation}\n 根据犯罪事实，判决结果，司法解释，生成的判决书。（仅输出判决书，其他内容均不输出）"
	response1 = predict.think(text3, stream=False)
	verdict = response1["output"]["choices"][0]["message"]["content"]
	
	return {
			"similar_cases":           case_list,
			"judgment_result":         judgment_result,
			"judicial_interpretation": judicial_interpretation,
			"verdict":                 verdict
	}


@app.get("/health")
async def health_check():
	return {"status": "healthy"}
